package com.toutiao.issue

import scala.collection.mutable.ArrayBuffer

import java.util.Date

class TimeArray {
  
  private
  val Ts = new ArrayBuffer[(String,Date)]
  
  def maxTime = 
    if (Ts.size == 0) SimpleDate.parse("2012-01-01 00:00:00")
    else Ts(Ts.size-1)._2
  
  def minTime = 
    if (Ts.size == 0) SimpleDate.parse("2012-01-01 00:00:00")
    else Ts(0)._2
    
  // 返回的是大于等于的第一个位置
  private
  def binarySearch(key:Date) = {
    var high = Ts.size
    var low = -1
    while (high-low > 1){
      val guess = (high+low)/2
      if (Ts(guess)._2.getTime < key.getTime)
        low = guess
      else
        high = guess
    }
    high
  }
  
  def before(key:Date) = {
    val i = binarySearch(key)
    if (i < Ts.size && i > 0)
      i
    else
      -1
  }
  
  def insert(name:String,key:Date) {
    val now = SimpleDate.current.getTime
    val t =
      if (key.getTime <= now)
        key
      else
        now
    if (Ts.size == 0 || Ts(Ts.size-1)._2.getTime <= key.getTime){
      Ts += ((name,key))
    } 
    else {
      val i = binarySearch(key)
      Ts.insert(i,(name,key))
    }    
  }
  
  def start(i:Int) = Ts.slice(0,i)
  
  def remove(i:Int) {
    if (i > 0 && i < Ts.size)
      Ts.trimStart(i)
  }
}
